package ua.yandex.shad.tempseries;

public class TemperatureSeriesAnalysis {

    class IllegalTemperatureValueException extends Exception {

    }

    public static final double TEMP_MIN = -273;
    private final double[] temperatureSeries;

    public TemperatureSeriesAnalysis(double[] temperatureSeries)
            throws IllegalTemperatureValueException {
        this.temperatureSeries = temperatureSeries;
        for (double d : temperatureSeries) {
            if (d < TEMP_MIN) {
                throw new IllegalTemperatureValueException();
            }
        }
    }

    public double calcAverageTemp() {
        double average = 0;
        for (double d : temperatureSeries) {
            average += d;
        }
        return average / temperatureSeries.length;
    }

    public double findTempClosestToZero() {
        double closest = temperatureSeries[0];
        for (double d : temperatureSeries) {
            if (Math.abs(d) < Math.abs(closest)) {
                closest = d;
            }
            if (Math.abs(d) == Math.abs(closest) && d > closest) {
                closest = d;
            }
        }
        return closest;
    }

    public double findTempClosestToValue(double tempValue) {
        double closest = temperatureSeries[0];
        for (double d : temperatureSeries) {
            if (Math.abs(d - tempValue) < Math.abs(closest - tempValue)) {
                closest = d;
            }
            if (Math.abs(d - tempValue) == Math.abs(closest - tempValue)
                    && d > closest) {
                closest = d;
            }
        }
        return closest;
    }

    public double[] findTempsLessThen(double tempValue) {
        int length = 0;
        for (double d : temperatureSeries) {
            if (d < tempValue) {
                length++;
            }
        }
        int i = 0;
        double[] tempsLessThen = new double[length];
        for (double d : temperatureSeries) {
            if (d < tempValue) {
                tempsLessThen[i++] = d;
            }
        }

        return tempsLessThen;
    }

    public double[] findTempsGreaterThen(double tempValue) {
        int length = 0;
        for (double d : temperatureSeries) {
            if (d > tempValue) {
                length++;
            }
        }
        int i = 0;
        double[] tempsGreaterThen = new double[length];
        for (double d : temperatureSeries) {
            if (d > tempValue) {
                tempsGreaterThen[i++] = d;
            }
        }

        return tempsGreaterThen;
    }

}
